package org.example.authentication.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.example.authentication.pojo.SysUser;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
//@RequestMapping("")
public class LoginController {

    @PostMapping(value ="/login")
    public String login(SysUser user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return "请输入用户名和密码！";
        }
        // 获取当前用户的 Subject 对象
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUsername(),
                user.getPassword()
        );
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
            // subject.hasRole("admin");
            // subject.isPermitted("add");
        } catch (UnknownAccountException e) {
            log.error("用户名不存在！", e);
            return "用户名不存在！";
        } catch (AuthenticationException e) {
            log.error("账号或密码错误！", e);
            return "账号或密码错误！";
        } catch (AuthorizationException e) {
            log.error("没有权限！", e);
            return "没有权限";
        }

        // 检查用户是否已认证
        if (subject.isAuthenticated()) {
            return "登录成功";
        } else {
            usernamePasswordToken.clear();
            return "登录失败";
        }
    }

    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "管理员访问成功!";
    }

    @RequiresPermissions("query")
    @GetMapping("/query")
    public String query() {
        return "查询成功!";
    }

    @RequiresPermissions("add")
    @GetMapping("/add")
    public String add() {
        return "添加成功!";
    }

    @GetMapping("/anon")
    public String anon(ServletRequest request) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Cookie[] cookies = httpServletRequest.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println("Found specific cookie: " + cookie.getName() + " = " + cookie.getValue());
        }

        return "anon enter!";
    }

}

